#!/usr/bin/env python
#-*- coding: utf-8 -*-

import objc
from core import Kelindo
import itertools

NSObject = objc.lookUpClass("NSObject")
bridge = objc.lookUpClass("BridgeClass")

class PythonStuff(NSObject):
    
    def init(self):
        super(PythonStuff, self).init()
    	return self
    
    def pyStartWithDict_(self, dict):
        print 'pyStartWithPath'

    	self.core = Kelindo(dict['path'])
        self.core.subscribe(self.__core_callbacks)
        if dict['conversion']:
            print 'only conv'
            self.core.find_candidate_only_conversion()
        else:
            self.core.find_candidate_albums()
        return
    
    def pyFinalizeWithDict_(self, dict):
        print 'pyFinalizeWithPath'
        new_albums = []
        for a in self.core.albums:
            if a.status == 'MATCH':
                new_albums.append(a)
        for f,b in itertools.izip(dict['albums'], new_albums):
            b.finalize = f['finalize']
    
        self.core.albums = new_albums
        move = False
        if dict['copy'] == 'Move files': move = True

        self.core.finalize_albums(dict['dest'], dict['format'].lower(), move)
        return

    def __core_callbacks(self, event):
        if event.key == 'candidate_no':
            print 'no candidate'
            return
    
        elif event.key == 'candidate_found':
            return
    
        elif event.key == 'candidate_done':
            self.core.classify_albums()
            return

        elif event.key == 'album_started' or event.key == 'album_found':
            dict = {'done' : event.done, 'total' : event.total}
            bridge.updateStatusBar_(dict)
            bridge.updateProgressBar_(dict)
            return

        elif event.key == 'album_done':
            results = []
            for a in self.core.albums:
                results.append(a.create_dict())
            bridge.finishedWithResults_(results)
            return

        elif event.key == 'finalize_started' or event.key == 'finalize_track_done':
            dict = {'done' : event.done, 'total' : event.total}
            bridge.updateStatusBar_(dict)
            bridge.updateProgressBar_(dict)
            return

        elif event.key == 'finalize_done':
            bridge.finalizeFinished()
            return
    
        return

